package com.sure.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.sure.dao.GroupMapper;
import com.sure.dao.RoleMapper;
import com.sure.dao.UserMapper;
import com.sure.dao.UserRoleMapper;
import com.sure.exception.MyException;
import com.sure.pojo.Group;
import com.sure.pojo.Role;
import com.sure.pojo.User;
import com.sure.pojo.UserAndGroup;
import com.sure.pojo.UserRoleKey;
import com.sure.utils.Config;
import com.sure.utils.Const;
import com.sure.utils.MD5;

@Service("UserService")
public class UserService {
	
	@Resource
	UserMapper userMapper;
	
	@Resource
	UserRoleMapper userRoleMapper;
	
	@Resource
	RoleMapper roleMapper;
	
	@Resource
	GroupMapper groupMapper;
	
	/**
	 * 获取用户列表
	 * @param pageNum
	 * @param pageSize
	 * @param param
	 * @return
	 */
	public List<UserAndGroup> getUsers(int pageNum, int pageSize, Map param){
		PageHelper.startPage(pageNum, pageSize);
		
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
		if(Config.getString("ADMINISTRATORS_USER_NAME", "admin").equals(session.getAttribute(Const.SESSION_USER_NAME))){ //超级管理员
		}else{ //普通用户
			Group userGroup = groupMapper.selectByPrimaryKey((Integer) session.getAttribute(Const.SESSION_USER_GROUP_ID));
			param.put("groupPath", userGroup.getGroupPath());
		}
		
		List<UserAndGroup> users = userMapper.queryUsers(param);
		
		return users;
	}
	
	/**
	 * 判断用户名是否存在
	 * @param userName
	 * @return
	 */
	public boolean checkUserNameExist(String userName){
		User user = userMapper.getUserByUserName(userName);
		
		return user == null;
	}
	
	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	public int addUser(User user){
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
		user.setUserPassword(MD5.md5(user.getUserPassword()));
		
		user.setCreateTime(new Date());
		
		user.setCreateBy((Integer) session.getAttribute(Const.SESSION_USER_ID));
		
		int result = userMapper.insertSelective(user);
		
		return result;
	}
	
	/**
	 * 编辑用户
	 * @param user
	 * @return
	 * @throws MyException 
	 */
	public int editUser(User user) throws MyException{
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
		User oldUser = userMapper.selectByPrimaryKey(user.getUserId());
		
		int oldGroupId = oldUser.getGroupId();
		
		if(oldGroupId != user.getGroupId()) { //变更了所属组织,检查用户是否和角色关联
			List<Integer> roleIds = userRoleMapper.queryRoleIdsByUserId(user.getUserId());
			if(roleIds.size() > 0) {
				throw new MyException("用户已分配角色,变更所属组织前请把用户角色清除");
			}
		}
		
		if(user.getUserPassword() != null && !user.getUserPassword().isEmpty()){
			user.setUserPassword(MD5.md5(user.getUserPassword()));
		}else{
			user.setUserPassword(null);
		}
		
		user.setUpdateTime(new Date());
		
		user.setUpdateBy((Integer) session.getAttribute(Const.SESSION_USER_ID));
		
		int result = userMapper.updateByPrimaryKeySelective(user);
		
		return result;
	}
	
	/**
	 * 删除用户
	 * @param userId
	 * @return
	 */
	@Transactional
	public int delUser(int userId){
		
		userRoleMapper.deleteByUserId(userId);
		
		return userMapper.deleteByPrimaryKey(userId);
	}
	
	/**
	 * 获取用户角色
	 * @param userId
	 * @return
	 */
	public List<Role> getUserRoles(int userId){
		return roleMapper.queryRolesByUserId(userId);
	}
	
	/**
	 * 分配用户角色
	 * @param userName
	 * @param roleIds
	 * @return
	 */
	@Transactional
	public int updateUserRoles(int userId, List<Integer> roleIds){
		userRoleMapper.deleteByUserId(userId);
		
		UserRoleKey userRole = new UserRoleKey();
		userRole.setUserId(userId);
		
		int count = 0;
		
		if(roleIds != null){
			for(int i=0,len=roleIds.size(); i<len; i++){
				userRole.setRoleId(roleIds.get(i));
				
				count += userRoleMapper.insert(userRole);
			}
		}
		
		return count;
	}
	
	/**
	 * 获取管理员与用户间的组织列表
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	public List<Group> getGroupsByUserBetween(int userId)throws Exception{
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		
		Group oneselfGroup = groupMapper.selectByPrimaryKey((Integer) session.getAttribute(Const.SESSION_USER_GROUP_ID));
		
		User user = userMapper.selectByPrimaryKey(userId);
		Group userGroup = groupMapper.selectByPrimaryKey(user.getUserId());
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("startPath", oneselfGroup.getGroupPath());
		param.put("endPath", userGroup.getGroupPath());
		
		return groupMapper.queryGroupsByPathBetween(param);
	}
}
